package cn.fanyamin.web.struts;


import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.LazyValidatorForm;

import cn.fanyamin.business.TaskService;
import cn.fanyamin.domain.UserCategory;
import cn.fanyamin.domain.RemindTask;
import cn.fanyamin.domain.RepeatInfo;
import cn.fanyamin.domain.RepeatVO;
import cn.fanyamin.domain.Task;
import cn.fanyamin.domain.TaskVO;
import cn.fanyamin.domain.User;

public class TaskAction extends SecureBaseAction {
	private static Log logger = LogFactory.getLog(TaskAction.class);
/*	@Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
	    
	    TaskService taskService = getWebApp().getTaskService();
	    List<Task> taskList = taskService.list();
	    request.setAttribute("taskList", taskList);
		logger.info("task: " + taskList);
        return (mapping.findForward("success"));
    }*/

	public ActionForward list(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
	    
	    int taskType = NumberUtils.toInt(request.getParameter("taskType"));
	    
	    TaskService taskService = getWebApp().getTaskService();
        User user = getUserFromSession(request);
	    List<Task> taskList = null;
	    
	    if(taskType==4) {
	        taskList = taskService.getFinishedTasks(user.getUserID());
	    } else if(taskType > 0) {
	        taskList = taskService.getTaskList(taskType, user.getUserID());
	    } else {
		    taskList = taskService.list(user.getUserID());
	    }
	    
	    request.setAttribute("taskList", taskList);
		logger.info("taskList: " + taskList);
		
		setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
		setContexts(request);
		
		if(taskType == Task.TASKTYPE_ONSCHEDULE) {
		    return mapping.findForward("calendar");
		} else if(taskType == 4) {
            return mapping.findForward("oldtask");
        }
        return mapping.findForward("list");

	}
	
	public ActionForward find(ActionMapping mapping, ActionForm form,
	                          HttpServletRequest request,
                              HttpServletResponse response) {

        TaskService taskService = getWebApp().getTaskService();
        User user = getUserFromSession(request);
        TaskVO vo = this.getTaskVO4Form(form);
        vo.setUserID(user.getUserID());
        
        Task task = new Task();
        //note: it's spring BeanUtils, not commons
        BeanUtils.copyProperties(vo, task);
       
        List<Task> taskList = taskService.findTasks(task);
        
        request.setAttribute("taskList", taskList);
        request.setAttribute("foundTask", task);
        
        logger.info("taskList: " + taskList);
        
        setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
        setContexts(request);

        return mapping.findForward("list");

    }
	
	public ActionForward create(ActionMapping mapping, ActionForm form,
	                            HttpServletRequest request, HttpServletResponse response) {
		TaskService taskService = getWebApp().getTaskService();
		
		User user = (User)request.getSession().getAttribute("sess_user");
		if(user == null) {
		    return mapping.findForward("failure");
		}
		
		TaskVO vo = getTaskVO4Form(form);
		vo.setUserID(user.getUserID());
		
	    taskService.createTask(vo);

		logger.info("create task: " + vo);
		return mapping.findForward("success");
	}
	
   
    private TaskVO getTaskVO4Form(ActionForm form) {
        LazyValidatorForm taskForm = (LazyValidatorForm) form;
        TaskVO vo = new TaskVO();
        //task
        vo.setTaskID(NumberUtils.toInt((String) taskForm.get("taskID")));
        vo.setTaskType(NumberUtils.toInt((String) taskForm.get("taskType")));
        vo.setContextID(NumberUtils.toInt((String) taskForm.get("contextID")));
        vo.setRepeatID(NumberUtils.toInt((String) taskForm.get("repeatID")));
        vo.setCategoryID(NumberUtils.toInt((String) taskForm.get("categoryID")));
        vo.setEnergy(NumberUtils.toInt((String) taskForm.get("energy")));

        vo.setTaskName(StringUtils.trim(""+taskForm.get("taskName")));
        vo.setDuration(NumberUtils.toInt((String) taskForm
                        .get("duration")));
        vo.setPriority(NumberUtils.toInt((String) taskForm.get("priority")));
        vo.setDescription(StringUtils.trim(""+taskForm.get("description")));

        String strDeadlline = (String) taskForm.get("deadline");
        String strCreateTime = (String) taskForm.get("createTime");
        String strBeginTime = (String) taskForm.get("beginTime");
        String strEndTime = (String) taskForm.get("endTime");
                
        if (StringUtils.isNotBlank(strDeadlline))
            vo.setDeadline(Timestamp.valueOf(strDeadlline));
        
        if (StringUtils.isNotBlank(strCreateTime))
            vo.setCreateTime(Timestamp.valueOf(strCreateTime));
        
        if (StringUtils.isNotBlank(strBeginTime))
            vo.setBeginTime(Timestamp.valueOf(strBeginTime));
        
        if (StringUtils.isNotBlank(strEndTime))
            vo.setEndTime(Timestamp.valueOf(strEndTime));
        
        //remind
        String strIsRemind = (String) taskForm.get("isRemind");
        boolean isRemind = "yes".equalsIgnoreCase(strIsRemind);
        vo.setRemind(isRemind);
        if(isRemind) {
            String strRemindTime = (String) taskForm.get("remindTime");
            vo.setRemindTime(Timestamp.valueOf(strRemindTime));            
        }
        
        //repeat
        String strIsRepeat = (String) taskForm.get("isRepeat");
        boolean isRepeat = "yes".equalsIgnoreCase(strIsRepeat);
        vo.setRepeat(isRepeat);
        if (isRepeat) {
            String repeatType = (String) taskForm.get("repeatType");
            if (StringUtils.isBlank(repeatType)) {
                repeatType = "daily";
            }
            int repeatInterval = NumberUtils.toInt((String) taskForm.get("repeatInterval"));

            vo.setRepeatType(repeatType);
            vo.setRepeatInterval(repeatInterval);
            //???
            vo.setRepeatBeginTime(vo.getBeginTime());
            String repeatEndType = (String) taskForm.get("repeatEndType");
            vo.setRepeatEndType(repeatEndType);
            if (repeatEndType.equalsIgnoreCase("hasEndDate")) {
                String strRepeatEndTime = (String) taskForm.get("repeatEndTime");
                if (StringUtils.isNotBlank(strRepeatEndTime)) {
                    Timestamp ts = Timestamp.valueOf(strRepeatEndTime);
                    vo.setRepeatEndTime(ts);
                }
                String strRepeatTimes = (String) taskForm.get("repeatTimes");
                if (StringUtils.isNotBlank(strRepeatTimes)) {
                    int times = NumberUtils.toInt(strRepeatTimes);
                    vo.setRepeatTimes(times);
                }
            }
        } 
        return vo;
    }

    
    
    public ActionForward retrieve(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        TaskService taskService = getWebApp().getTaskService();
        LazyValidatorForm taskFrom = (LazyValidatorForm)form;
        int taskID = NumberUtils.toInt((String)taskFrom.get("taskID"));
        Task task = taskService.retrieve(taskID);
        request.setAttribute("task", task);
        if(task.getRepeatID()>0) {
        	RepeatInfo ri = taskService.retrieveRepeatInfo(task.getRepeatID());
        	request.setAttribute("repeatInfo", ri);
        }
        if(taskService.getSubTaskCount(taskID) > 0 ) {
        	List<Task> subTaskList = taskService.getSubTaskList(taskID);
        	request.setAttribute("subTaskList", subTaskList);
        }
        setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
        setContexts(request);
        
        return new ActionForward("/WEB-INF/jsp/struts/task/taskInfo.jsp");
    }
    
    public ActionForward update(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        
        TaskService taskService = getWebApp().getTaskService();
        TaskVO vo = getTaskVO4Form(form);
                
        taskService.updateTask(vo);
          
        logger.info("update task, task=" + vo);
        return mapping.findForward("success");
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        TaskService taskService = getWebApp().getTaskService();
        LazyValidatorForm taskFrom = (LazyValidatorForm)form;
        int taskID = NumberUtils.toInt((String)taskFrom.get("taskID"));
        taskService.delete(taskID);
        logger.info("delete task, taskID=" + taskID);
        return mapping.findForward("success");
    }
    
    public ActionForward finish(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
		TaskService taskService = getWebApp().getTaskService();
		LazyValidatorForm taskFrom = (LazyValidatorForm) form;
		int taskID = NumberUtils.toInt((String) taskFrom.get("taskID"));
		taskService.finishTask(taskID);
		logger.info("delete task, taskID=" + taskID);
		return mapping.findForward("success");
}    
    
    public ActionForward add(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
    	logger.info("add task");
    	
    	setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
    	setContexts(request);
    	
    	return mapping.findForward("add");
    }
    
    public ActionForward edit(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        TaskService taskService = getWebApp().getTaskService();
        LazyValidatorForm taskFrom = (LazyValidatorForm)form;
        int taskID = NumberUtils.toInt((String)taskFrom.get("taskID"));
        Task task = taskService.retrieve(taskID);
        request.setAttribute("task", task);
        if(task.getRepeatID()>0) {
        	RepeatInfo ri = taskService.retrieveRepeatInfo(task.getRepeatID());
        	request.setAttribute("repeatInfo", ri);
        }
        if(taskService.getSubTaskCount(taskID) > 0 ) {
        	List<Task> subTaskList = taskService.getSubTaskList(taskID);
        	request.setAttribute("subTaskList", subTaskList);
        }
        setCategories(request, UserCategory.CATEGORY_TYPE_TASK);
        setContexts(request);
        
        return mapping.findForward("edit");
    }
}
